package com.ec.core.dao;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import com.ec.core.annotation.Transactional;
import com.ec.core.util.Logging;

public class MethodInterceptorImpl implements MethodInterceptor {
	public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
		Annotation[] methodAnno = method.getDeclaredAnnotations();
		if(methodAnno!=null){
			for(Annotation mAnno:methodAnno){
				if(mAnno instanceof Transactional){
					com.ec.core.dao.Transaction tx = null;
					DaoEntity dao = (DaoEntity)obj;
			    	try{
			    		tx = dao.beginTransaction();
			    		Object object =  proxy.invokeSuper(obj, args);
			    		tx.commit();
			    		return object;
			    	}catch(Exception e){
			    		Logging.getLog("dao").error("transactional error:",e);
			    		tx.rollback();
			    	}finally{
			    		if(tx!=null) tx.close();
			    	}
			    	return null;
				}
			}
		}
		return proxy.invokeSuper(obj, args);
	}
}
